package com.zhongwang.mms.module.buy.model;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RedHeadStyleHandler implements RowWriteHandler {

    // 缓存需要染红的列索引
    private final Set<Integer> redColumns = new HashSet<>();

    public RedHeadStyleHandler(Class<?> clazz) {
        // 解析实体类，记录哪些列需要红色背景
        Field[] fields = clazz.getDeclaredFields();
        int col = 0;
        for (Field f : fields) {
            if (f.isAnnotationPresent(RedHead.class)) {
                redColumns.add(col);
            }
            if (f.isAnnotationPresent(ExcelProperty.class)) {
                col++; // 只统计带 @ExcelProperty 的字段
            }
        }
    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                               Row row, Integer relativeRowIndex, Boolean isHead) {
        if (!Boolean.TRUE.equals(isHead)) return; // 只处理表头行

        Sheet sheet = writeSheetHolder.getSheet();
        Workbook workbook = sheet.getWorkbook();

        for (Integer colIndex : redColumns) {
            Cell cell = row.getCell(colIndex);
            if (cell == null) continue;

            CellStyle style = workbook.createCellStyle();
            // 复制原样式（字体、边框等）
            style.cloneStyleFrom(cell.getCellStyle());

            // 设置红色背景
            style.setFillForegroundColor(IndexedColors.RED.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            cell.setCellStyle(style);
        }
    }
}
